﻿using System;
using System.Globalization;
using GammaJul.ReSharper.GammaXaml.Highlightings.CSharp;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.LinqTools;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.TextControl;
using JetBrains.Util;

namespace GammaJul.ReSharper.GammaXaml.QuickFixes.CSharp {

	/// <summary>
	/// Replaces a dependency property default value with its default property type value.
	/// </summary>
	[QuickFix]
	public class UseDefaultValueTypeFix : QuickFixBase {
		private readonly MismatchedDpDefaultValueTypeHighlighting _highlighting;

		public override string Text {
			get {
				return String.Format(
					CultureInfo.CurrentCulture,
					"Use 'default({0})'",
					_highlighting.DpRegisteredType.GetPresentableName(CSharpLanguage.Instance));
			}
		}

		protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) {
			var elementFactory = CSharpElementFactory.GetInstance(_highlighting.DefaultValueArgument.PsiModule);
			_highlighting.DefaultValueArgument.Expression.ReplaceBy(
				elementFactory.CreateExpression("default($0)", elementFactory.CreateTypeUsageNode(_highlighting.DpRegisteredType)));

			return null;
		}

		public override bool IsAvailable(IUserDataHolder cache) {
			return _highlighting.IsValid();
		}

		public UseDefaultValueTypeFix([NotNull] MismatchedDpDefaultValueTypeHighlighting highlighting) {
			if (highlighting == null)
				throw new ArgumentNullException("highlighting");
			_highlighting = highlighting;
		}
	}

}